package com.example.pojo.utils;

import cn.hutool.core.util.ObjectUtil;
import com.example.pojo.entity.Admin;
import com.example.pojo.entity.Permission;
import com.example.pojo.entity.Role;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.*;

/**
 * TODO
 *
 * @author ding
 * @since 2024/7/23
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class LoginUser implements UserDetails {

    //用户信息
    private Admin admin;

    public LoginUser(Admin admin) {
        this.admin = admin;
    }

    private List<SimpleGrantedAuthority> authorities;

    /**
     * 获取权限信息
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (!ObjectUtil.isEmpty(authorities)){
            return authorities;
        }

        //将权限信息封装成SimpleGrantedAuthority对象
        authorities = new ArrayList<>();

        Set<Role> roles = admin.getRoles();
        roles.forEach(role -> {
            //授权角色信息
            authorities.add(new SimpleGrantedAuthority(role.getRoleValue()));
            Set<Permission> permissions = role.getPermissions();
            permissions.forEach(permission -> {
                //授权权限信息
                authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
            });
        });

        return authorities;
    }

    @Override
    public String getPassword() {
        return admin.getPassword();
    }

    @Override
    public String getUsername() {
        return admin.getUsername();
    }

    /**
     * 判断是否过期
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 是否锁定
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 是否没有超时
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return admin.getStatus() == 1;
    }
}
